package com.example.applicationnews;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

public class MyFragment extends androidx.fragment.app.ListFragment {
    private static final String TAG = "MyFragment";
    private ArrayAdapter<String> adapter;
    private final ArrayList<Stars> starsArrayList = new ArrayList<Stars>();
    private FragmentManager fManager;
    private ListView list_news;
    private final int listView_position;
    private boolean isGetData = false;
    private final Context context;
    private static final int[] TAB_TITLES = new int[] {R.string.tab_text_1, R.string.tab_text_2, R.string.tab_text_3, R.string.tab_text_4, R.string.tab_text_5};

    public MyFragment(int position, Context context) {
        this.listView_position = position + 1;
        this.context = context;
    }

    // 创建view
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my, container, false);
        list_news = (ListView) view.findViewById(R.id.listView);
        // 初始化 starsArrayList
        initialStarsArrayList();
        //
        MyAdapter myAdapter = new MyAdapter(starsArrayList, getActivity());
        setListAdapter(myAdapter);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onListItemClick(@NonNull ListView l, @NonNull View v, int position, long id) {
        // 单击时将每个新闻项目的相关数据打包在 bundle 里，传递给 activity
        Intent intent = new Intent(context, NewsDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("type", getResources().getString(TAB_TITLES[listView_position-1]));
        bundle.putString("item", String.valueOf(position));
        bundle.putString("url", starsArrayList.get(position).getNews_url());
        bundle.putString("author_name", starsArrayList.get(position).getNews_author());
        bundle.putString("title", starsArrayList.get(position).getNews_title());
        bundle.putString("pic", starsArrayList.get(position).getNews_pic());
        intent.putExtras(bundle);
        Log.d(TAG, "onListItemClick: "+ position);
        startActivity(intent);
        super.onListItemClick(l, v, position, id);
    }

    private void initialStarsArrayList() {
        // 通过文件名从本地读取相应文件
        String json = getNews(type(listView_position) + ".json");
        // 解码相应 json 内容并存储到 starsArrayList
        decodeJson(json);
    }

    public String getNews(String fileName){
        String result = "";
        FileHelper fHelper2 = new FileHelper(context.getApplicationContext());
        try {
            result = fHelper2.read(fileName);
            Log.d(TAG, "getNews: 成功");
        } catch (IOException e) {
            e.printStackTrace();
            Log.d(TAG, "getNews: 失败");
        }
        Log.d(TAG, "getNews: " + result);
        return result;
    }

    public String getFromAssets(String fileName){
        try {
            InputStreamReader inputReader = new InputStreamReader( getResources().getAssets().open(fileName) );
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line="";
            StringBuilder Result= new StringBuilder();
            while((line = bufReader.readLine()) != null) {
                Result.append(line);
            }
            Log.d(TAG, "getFromAssets: " + Result);
            return Result.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void imageCache(final String src) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(src);
                    InputStream is = url.openStream();
                    //截取最后的文件名
                    String end = src.substring(src.lastIndexOf("."));
                    //打开手机对应的输出流,输出到文件中
                    OutputStream os = context.openFileOutput(src, Context.MODE_PRIVATE);
                    byte[] buffer = new byte[1024];
                    int len = 0;
                    //从输入六中读取数据,读到缓冲区中
                    while((len = is.read(buffer)) > 0)
                    {
                        os.write(buffer,0,len);
                    }
                    //关闭输入输出流
                    is.close();
                    os.close();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void decodeJson (String response) {
        try{
            /*json格式的数据格式如下
                        {
                            "start":1,
                            "data:[
                                {},
                                {},
                                ...
                                ]
                        }
             */
            // Log.d(TAG, "decodeJson: start||" + response);
            // 将字符串类型的 json 数据 实例化成 上述的 json 数据格式
            if (!TextUtils.isEmpty(response)){
                JSONObject json_1 = new JSONObject(response);
                JSONArray jsonArray = json_1.getJSONArray("data");
                // Log.d(TAG, "decodeJson: " + json_1);
                // 找到存放数据的 data 对象

                for(int i = 0;i < jsonArray.length();i++){
                    // 将每个 item 的值赋值给 实例化的 stars 类型
                    // 再添加到 starsArrayList 中去
                    JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                    Stars stars = new Stars();
                    stars.setNews_author(jsonObject.getString("author_name"));
                    stars.setNews_title(jsonObject.getString("title"));
                    stars.setNews_pic(jsonObject.getString("thumbnail_pic_s"));
                    stars.setNews_url(jsonObject.getString("url"));
                    stars.setNews_time(jsonObject.getString("date"));
                    starsArrayList.add(stars);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            Log.d(TAG, "decodeJson: error " + e);
        }
    }


    private String type(int position) {
        // 根据 position 返回每个新闻分类的名字
        switch (position) {
            case 1:
                return "shehui";
            case 2:
                return "yule";
            case 3:
                return "xiaohua";
            case 4:
                return "guonei";
            case 5:
                return "guoji";
            default:
                return "";
        }
    }
}